package timer

import (
	"time"
)

/*
如果发进来的时间变化
FrameDeltaTime
比这个大，按这个倍率来生成时间
*/
type TimeTicker struct {
	currenttime    int64
	lasttime       int64
	tick           int32
	FrameDeltaTime int64 //希望帧的时间间隔
	nowv           int64
	num            int64
	count          int64
}

func NewTimeTicker(now time.Time, frame int64) *TimeTicker {
	return &TimeTicker{
		currenttime:    now.UnixMilli(),
		lasttime:       now.UnixMilli(),
		tick:           0,
		FrameDeltaTime: frame,
	}
}

func (this *TimeTicker) TimeTick(now time.Time) time.Time {
	nowv := now.UnixMilli()
	// logger.Debugf(logger.LogKey_Default, "TimeTick Now %d %d %d %d", this.nowv, nowv, time.Now().UnixMilli(), nowv-this.nowv)
	// if this.nowv != 0 {
	// 	this.num += nowv - this.nowv
	// 	this.count++
	// }
	// this.nowv = nowv
	// if this.count > 0 {
	// 	logger.Debugf(logger.LogKey_Default, "TimeTick Count %d %d %d", this.num, this.count, this.num/this.count)
	// }
	if nowv == this.lasttime {
		return time.UnixMilli(this.currenttime)
	}
	step := (nowv - this.currenttime) / this.FrameDeltaTime
	if step <= 0 {
		step = 1
		// this.tick = 0
		// logger.Debug(logger.LogKey_Default, nowv, this.currenttime)
		// return
	}
	this.currenttime += step * this.FrameDeltaTime
	this.tick = int32(this.currenttime - this.lasttime)
	// logger.Debugf(logger.LogKey_Default, "TimeTick %d %d (%d) %d %d ", nowv, this.currenttime, this.currenttime-nowv, this.lasttime, this.tick)
	// 	if nowv < this.currenttime {
	// 	logger.Debugf(logger.LogKey_Default, "TimeTick %d %d (%d) %d %d ", nowv, this.currenttime, this.currenttime-nowv, this.lasttime, this.tick)
	// } else {
	// 	logger.Debug(logger.LogKey_Default, "TimeTick")
	// }
	return time.UnixMilli(this.currenttime)
}

func (this *TimeTicker) EndTick() {
	this.lasttime = this.currenttime
}

func (this *TimeTicker) GetDeltaTime() int32 {
	return this.tick
}

func (this *TimeTicker) GetDeltaTimeF() float32 {
	return float32(this.tick) * 0.001
}

func (this *TimeTicker) GetCurTime() int64 {
	return this.currenttime
}

func (this *TimeTicker) GetCurTimeS() int64 {
	return this.currenttime / 1000
}
